var Promise = require('../lib/bluebird.min')
const mapKey = "QRm5G6OEkBSMYSgSIrhNKmzpjsH6epF7"
const defaultImage = "http://hiphotos.baidu.com/space/pic/item/37d3d539b6003af3ca5c8d773d2ac65c1138b6c7.jpg"
//获取周边位置商户信息
export function getAroundInfos(data) {
  wx.request({
    url: 'http://api.map.baidu.com/place/v2/search',
    data: {
      query: data.query,
      location: data.location.lat + "," + data.location.lng,
      ak: mapKey,
      scope: 2,
      radius: 2000,
      output: "json"
    },
    method: 'GET',
    success: function(res) {
      if (res.statusCode === 200) {
        res = res.data.results;
        data.success(res);
      }
    },
    fail: function() {
      // fail
    },
    complete: function() {
      // complete
    }
  })

}

//获取商户列表详情信息
export function getShopDetails(datas) {
  const {
    data,
    success
  } = datas;
  //添加图片地址
  var arr = []
  dowithShopDetail(data, arr).then(
    v => success(v),
    e => console.log(e)
  )

}
//获得单个商品详细信息
export function shopDetail(uid) {

  return new Promise((resolve, reject) => {
    wx.request({
      url: 'http://map.baidu.com/detail?qt=ninf',
      data: {
        uid: uid
      },
      method: 'GET',
      success: function(res) {
        try {
          console.log(res)
          resolve (res.data.content)
        } catch (error) {
          console.log(error)
        }
        
      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
      }
    })
  })

}
//添加商户详情图片
function dowithShopDetail(ins, arr) {
  return new Promise((resolve, reject) => {
    ins.map(((item, index) => {
      let uid = item.uid
      wx.request({
        url: 'http://map.baidu.com/detail?qt=ninf',
        data: {
          uid: uid
        },
        method: 'GET',
        success: function(res) {
          try {
            arr.push(Object.assign({}, item, {
              image: res.data.content.ext.detail_info.image
            }))
          } catch (error) {
            arr.push(Object.assign({}, item, {
              image: defaultImage
            }))
          }
          if (arr.length == ins.length) {
            resolve(arr)
          }
        },
        fail: function() {
          // fail
        },
        complete: function() {
          // complete
        }
      })

    }))
  })

}